package com.lingyue.commons.encrypt;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DESEncryptUtils {

    private final static String DES_RULE = "DESede/ECB/PKCS5Padding";
    private final static String DES_EDE = "DESede";
    private final static String UTF_8 = "UTF-8";
    private final static String ASCII = "ASCII";
    private static Cipher DES_CIPHER;

    static {
        try {
            DES_CIPHER = Cipher.getInstance(DES_RULE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String content, String encryptKey) throws Exception {
        DES_CIPHER.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(ASCII), DES_EDE));
        byte[] encryptedData = DES_CIPHER.doFinal(content.getBytes());
        return Base64.getMimeEncoder().encodeToString(encryptedData);
    }

    public static String decrypt(String encrypt, String decryptKey) throws Exception {
        DES_CIPHER.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(ASCII), DES_EDE));
        byte[] decode = Base64.getMimeDecoder().decode(encrypt);
        byte[] decryptedData = DES_CIPHER.doFinal(decode);
        return new String(decryptedData, UTF_8);
    }

    public static void main(String[] args) {
        String key = ":5J8tU6zsHeLGtEuH;^4#eU~";
        String encrypt = "gQRkvqjtb+vEPa1bMwxPn+2zW/Jibft8nZodb7y7XNZRPlF5rUxCJmFvi8xHP1MXS6or4dYd5ViD5Szc3DfDsAhp1jmeOqcyPdcTNyLCtpE6urtfqpxQG7qX/c8SsvzcvpUWkuV4T+odVacpMwg/uLa/WtY43csy";

        try {
            String decrypt = decrypt(encrypt, key);
            System.out.println(decrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
